package vn.hanelsoft.newsduet.model.adapter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import vn.hanelsoft.newsduet.R;
import vn.hanelsoft.newsduet.common.ConstCommon;
import vn.hanelsoft.newsduet.common.UtilsCommon;
import vn.hanelsoft.newsduet.control.DetailActivity;
import vn.hanelsoft.newsduet.model.object.ObjectCategory;
import vn.hanelsoft.newsduet.model.object.ObjectNews;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;

public class AdapterFavouriteNews extends BaseAdapter implements OnClickListener {
	private LayoutInflater mInflater;
	private ArrayList<ObjectCategory> data; // key // dataSend dung de gui qua
	// activity Details
	private ImageLoader imageLoader1, imageLoader2;
	private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
	private Context mContext;
	private DisplayImageOptions options1;
	public ViewHolder holder;

	@SuppressWarnings("deprecation")
	public AdapterFavouriteNews(Context context) {

		mContext = context;
		mInflater = LayoutInflater.from(context);
		this.data = new ArrayList<ObjectCategory>();
		new ArrayList<Integer>();

		imageLoader1 = ImageLoader.getInstance();
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				context).threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				.discCacheFileNameGenerator(new Md5FileNameGenerator())
				.tasksProcessingOrder(QueueProcessingType.LIFO).build();
		imageLoader1.init(config);

		imageLoader2 = ImageLoader.getInstance();
		imageLoader2.init(config);

		options1 = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.ic_stub2).cacheInMemory(true)
				.cacheOnDisc(true).showImageForEmptyUri(R.drawable.ic_stub2)
				// .showImageOnFail(R.drawable.img_demo).cacheInMemory()
				.cacheOnDisc().resetViewBeforeLoading(false) // default
				.imageScaleType(ImageScaleType.EXACTLY) // default
				.bitmapConfig(Bitmap.Config.ARGB_8888) // default
				.displayer(new SimpleBitmapDisplayer()) // default
				.handler(new Handler()) // default
				.build();

	}

	public void setData(ArrayList<ObjectCategory> data) {
		this.data = data;
	}

	@Override
	public int getCount() {

		// ham tinh so hang
		int count = 0;
		for (int i = 0; i < data.size(); i++) {
			int size = data.get(i).getCategory_listNews().size();
			if (size > 3) {
				count++;
				size -= 3;
			}
			count += size / 2;
			if (size % 2 == 1) {
				count++;
			}
		}
		return count;
	}

	public int getCategoryPosition(int position) {

		// ham tinh so hang
		int count = 0;
		for (int i = 0; i < data.size(); i++) {
			int size = data.get(i).getCategory_listNews().size();
			if (size > 3) {
				count++;
				size -= 3;
			}
			count += size / 2;
			if (size % 2 == 1) {
				count++;
			}
			if (count > position) {
				return i;
			}
		}
		return 0;
	}

	public int getItemPosition(int position) {

		// ham tinh so hang
		int count = 0;
		int countCategory = 0;
		for (int i = 0; i < data.size(); i++) {
			int size = data.get(i).getCategory_listNews().size();
			if (size > 3) {
				countCategory=1;
				size -= 3;
			}
			countCategory += size / 2;
			if (size % 2 == 1) {
				countCategory++;
			}
			count+= countCategory;

			if (count > position) {
				count-= countCategory;
				int j = position - count;
				if (j == 0) {
					return 0;
				} else if (j == 1) {
					return 3;
				} else if (j > 1) {
					j--;
					return 3 + 2 * j;
				}
			}
			countCategory = 0;
		}
		return 0;
	}

	public int getItemPosition(int _i, int _j) {

		// ham tinh so hang
		int count = 0;
		if (_i < data.size()) {
			for (int i = 0; i < _i; i++) {
				int size = data.get(i).getCategory_listNews().size();
				count += size;
			}
			if (_j < data.get(_i).getCategory_listNews().size()) {
				count += _j;
			}
		}
		return count;
	}

	@Override
	public Object getItem(int position) {
		int i = 0;
		int j = position;
		for (; i < data.size(); i++) {
			int size = data.get(i).getCategory_listNews().size();
			if (j >= size) {
				j -= size;
			} else {
				break;
			}
		}
		return data.get(i).getCategory_listNews().get(j);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	public void notifydata(ArrayList<ObjectCategory> data) {
		this.data = data;
		notifyDataSetChanged();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = mInflater.inflate(R.layout.item_fg_home, null);
			convertView.setTag(holder);
			// 0
			holder.group1 = (RelativeLayout) convertView
					.findViewById(R.id.Group1);
			holder.group2 = (LinearLayout) convertView
					.findViewById(R.id.Group2);
			holder.group22 = (RelativeLayout) convertView
					.findViewById(R.id.Group22);

			// 1
			holder.txt_item1_tittle = (TextView) convertView
					.findViewById(R.id.item_title_title);
			holder.txt_item1_name = (TextView) convertView
					.findViewById(R.id.item_title_name);
			holder.txt_item1_description = (TextView) convertView
					.findViewById(R.id.item_title_description);
			holder.txt_item1_date = (TextView) convertView
					.findViewById(R.id.item_title_date);
			holder.img_item1 = (ImageView) convertView
					.findViewById(R.id.item_title_image);

			holder.img_item1.setOnClickListener(this);

			// 2
			holder.txt_item2_name = (TextView) convertView
					.findViewById(R.id.item_no_title_name1);
			holder.txt_item2_date = (TextView) convertView
					.findViewById(R.id.item_no_title_date1);
			holder.img_item2 = (ImageView) convertView
					.findViewById(R.id.item_no_title_image1);

			holder.img_item2.setOnClickListener(this);

			// 3
			holder.txt_item3_name = (TextView) convertView
					.findViewById(R.id.item_no_title_name2);
			holder.txt_item3_date = (TextView) convertView
					.findViewById(R.id.item_no_title_date2);
			holder.img_item3 = (ImageView) convertView
					.findViewById(R.id.item_no_title_image2);

			holder.img_item3.setOnClickListener(this);

		} else
			holder = (ViewHolder) convertView.getTag();

		int i = getCategoryPosition(position);
		int j = getItemPosition(position);
		int z = getItemPosition(i, j);

		if (i < data.size()) {
			if (j == 0) {
				// title
				ObjectNews item = data.get(i).getCategory_listNews().get(j);
				ObjectNews item1;
				ObjectNews item2;

				holder.img_item1.setTag(z);
				holder.img_item2.setTag(z + 1);
				holder.img_item3.setTag(z + 2);

				holder.group1.setVisibility(View.VISIBLE);
				holder.txt_item1_tittle.setText(item.getNews_name_category());
				holder.txt_item1_name.setText(item.getNews_title());
				holder.txt_item1_description.setText(UtilsCommon.convertDescriptionToSummary(item.getNews_description()));
				holder.txt_item1_date.setText(item.getNews_pubDate());
				String url = item.getNews_imageSRC();
				if(url.equals(""))
				{
					url = getStringURLImageFromDrawble(item);
				}
				
				imageLoader1.displayImage(url, holder.img_item1,
						options1, animateFirstListener);

				if (j + 1 < data.get(i).getCategory_listNews().size()) {
					item1 = data.get(i).getCategory_listNews().get(j + 1);
					holder.group2.setVisibility(View.VISIBLE);
					imageLoader1.displayImage(item1.getNews_imageSRC(),
							holder.img_item2, options1, animateFirstListener);
					holder.txt_item2_name.setText(item1.getNews_title());
					holder.txt_item2_date.setText(item1.getNews_pubDate());
					
					String url1 = item1.getNews_imageSRC();
					if(url1.equals(""))
					{
						url1 = getStringURLImageFromDrawble(item1);
					}
					
					imageLoader1.displayImage(url1, holder.img_item2,
							options1, animateFirstListener);

					if (j + 2 < data.get(i).getCategory_listNews().size()) {
						item2 = data.get(i).getCategory_listNews().get(j + 2);
						holder.group22.setVisibility(View.VISIBLE);
						imageLoader1.displayImage(item2.getNews_imageSRC(),
								holder.img_item3, options1,
								animateFirstListener);
						holder.txt_item3_name.setText(item2.getNews_title());
						holder.txt_item3_date.setText(item2.getNews_pubDate());
						String url2 = item1.getNews_imageSRC();
						if(url2.equals(""))
						{
							url2 = getStringURLImageFromDrawble(item2);
						}
						imageLoader1.displayImage(url2, holder.img_item3,
								options1, animateFirstListener);
					} else {
						holder.group22.setVisibility(View.GONE);
					}
				} else {
					holder.group2.setVisibility(View.GONE);
				}
			} else {
				// no title
				holder.group1.setVisibility(View.GONE);
				if(j < data.get(i).getCategory_listNews().size())
				{
					ObjectNews item1 = data.get(i).getCategory_listNews().get(j);
					ObjectNews item2;

					holder.img_item2.setTag(z);
					holder.img_item3.setTag(z + 1);

					holder.group2.setVisibility(View.VISIBLE);
					imageLoader1.displayImage(item1.getNews_imageSRC(), holder.img_item2,
							options1, animateFirstListener);
					holder.txt_item2_name.setText(item1.getNews_title());
					holder.txt_item2_date.setText(item1.getNews_pubDate());
					String url1 = item1.getNews_imageSRC();
					if(url1.equals(""))
					{
						url1 = getStringURLImageFromDrawble(item1);
					}
					imageLoader1.displayImage(url1, holder.img_item2,
							options1, animateFirstListener);

					if (j + 1 < data.get(i).getCategory_listNews().size()) {
						item2 = data.get(i).getCategory_listNews().get(j + 1);
						holder.group22.setVisibility(View.VISIBLE);
						imageLoader1.displayImage(item2.getNews_imageSRC(),
								holder.img_item3, options1, animateFirstListener);
						holder.txt_item3_name.setText(item2.getNews_title());
						holder.txt_item3_date.setText(item2.getNews_pubDate());
						String url2 = item2.getNews_imageSRC();
						if(url2.equals(""))
						{
							url2 = getStringURLImageFromDrawble(item2);
						}
						imageLoader1.displayImage(item2.getNews_imageSRC(), holder.img_item3,
								options1, animateFirstListener);
					} else {
						holder.group22.setVisibility(View.GONE);
					}
				}else {
					holder.group2.setVisibility(View.GONE);
					holder.group22.setVisibility(View.GONE);
				}
				
			}
		}

		// Utils.setAppFont(mContext, (ViewGroup) convertView, Const.FONT_NAME);
		return convertView;
	}

	class ViewHolder {
		// private TextView txtNo_photo;

		LinearLayout group2;
		RelativeLayout group1, group22;
		TextView txt_item1_tittle, txt_item1_name, txt_item1_description,
				txt_item1_date, txt_item2_name, txt_item2_date, txt_item3_name,
				txt_item3_date;
		ImageView img_item1, img_item2, img_item3;

	}

	void startActivity(int pos) {
		 Intent mIntent2 = new Intent(mContext, DetailActivity.class)
		 .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		 mIntent2.putExtra(ConstCommon.DETAIL_DATA_LIST_OBJECT, data);
		 mIntent2.putExtra(ConstCommon.DETAIL_DATA_POSITION, pos);
		 mContext.getApplicationContext().startActivity(mIntent2);
	}

	private static class AnimateFirstDisplayListener extends
			SimpleImageLoadingListener {

		static final List<String> displayedImages = Collections
				.synchronizedList(new LinkedList<String>());

		@Override
		public void onLoadingComplete(String imageUri, View view,
				Bitmap loadedImage) {
			if (loadedImage != null) {
				ImageView imageView = (ImageView) view;
				boolean firstDisplay = !displayedImages.contains(imageUri);
				if (firstDisplay) {
					FadeInBitmapDisplayer.animate(imageView, 500);
					displayedImages.add(imageUri);
				}
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.item_title_image:
			startActivity((Integer) v.getTag());
			break;
		case R.id.item_no_title_image1:
			startActivity((Integer) v.getTag());
			break;
		case R.id.item_no_title_image2:
			startActivity((Integer) v.getTag());
			break;
		default:
			break;
		}
	}

	String getStringURLImageFromDrawble(ObjectNews objectNews)
	{
		String strUrl = "drawable://" + R.drawable.ic_launcher;
		String strNameCategory = objectNews.getNews_name_category().toString().trim();
		
		if(strNameCategory.equals("India"))
		{
			strUrl = "drawable://" + R.drawable.icon_india;
		}else if(strNameCategory.equals("World"))
		{
			strUrl = "drawable://" + R.drawable.icon_world;
		}else if(strNameCategory.equals("Business"))
		{
			strUrl = "drawable://" + R.drawable.icon_business;
		}else if(strNameCategory.equals("Technology"))
		{
			strUrl = "drawable://" + R.drawable.icon_tech;
		}else if(strNameCategory.equals("Health"))
		{
			strUrl = "drawable://" + R.drawable.icon_health;
		}else if(strNameCategory.equals("Science"))
		{
			strUrl = "drawable://" + R.drawable.icon_science;
		}else if(strNameCategory.equals("Sports"))
		{
			strUrl = "drawable://" + R.drawable.icon_sport;
		}
		
		return strUrl;
	}
	
}

